package com.rcloud.server.sealtalk.manager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rcloud.server.sealtalk.constant.ErrorCode;
import com.rcloud.server.sealtalk.exception.ServiceException;
import com.rcloud.server.sealtalk.xiangyun.NetOCRCommonClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: zc
 * @date: 2021/06/16
 * @description: OCR处理类
 * @copyright (c) 20201, rongcloud.cn All Rights Reserved
 */
@Slf4j
@Service
public class NetOCRManager extends BaseManager {
    @Resource
    private NetOCRCommonClient ocrCommonClient;

    /**
     * 用户身份证OCR识别处理
     */
    public Map<String, Object> idCardRecognizeHandle(MultipartFile file, String regType) throws ServiceException {
        log.info("用户身份证OCR识别处理.file:[{}]", file.getOriginalFilename());
        Map<String, Object> map = new HashMap<>();
        try {
            String result = ocrCommonClient.identifyCert(file,regType);
            log.info("用户身份证OCR识别处理result:" + result);
            //转换json数据，处理json信息
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject message = jsonObject.getJSONObject("message");
            //查询成功
            if (message.getIntValue("status") == 2 || message.getIntValue("status") == 3) {
                JSONObject cardsinfo = jsonObject.getJSONArray("cardsinfo").getJSONObject(0);
                //查询内部的信息
                JSONArray items = cardsinfo.getJSONArray("items");
                // 身份证正面
                if ("2".equals(regType)) {
                    for (int i = 0; i < items.size(); i++) {
                        JSONObject json = items.getJSONObject(i);
                        if ("姓名".equals(json.getString("desc"))) {
                            map.put("name", json.getString("content"));
                        }
                        if ("公民身份号码".equals(json.getString("desc"))) {
                            map.put("idCard", json.getString("content"));
                        }
                    }
                }
                // 身份证背面
                if ("3".equals(regType)) {
                    for (int i = 0; i < items.size(); i++) {
                        JSONObject json = items.getJSONObject(i);
                        if ("有效期限".equals(json.getString("desc"))) {
                            map.put("validDate", json.getString("content"));
                        }
                    }
                }
            } else {
                throw new ServiceException(ErrorCode.IDENTIFY_CARD_ERROR, message.getString("value"));
            }
        } catch (IOException e) {
            log.error("证件识别出现错误" + e.getMessage());
            e.printStackTrace();
        }
        return map;
    }


}